package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup>implements SpecGroupService {


    //TODO 单条增删改不需要添加业务,多条需要添加事务注解,因为万一失败时需要同时回滚事务
    //添加规格组
    @Override
    @Transactional
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        boolean save = this.save(specGroup);
        if(!save){
            throw  new LyException(500,"新增规格组失败");
        }
    }
    //修改规格组
    @Override
    @Transactional
    public void updateSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        boolean b = this.updateById(specGroup);
        if(!b){
            throw  new LyException(500,"修改规格组失败");
        }
    }
    //根据分类ID查询规格参数组集合
    @Override
    public List<SpecGroupDTO> listSpecGroupByCid(Long cid) {

        List<SpecGroup> specGroups = this.query().eq("category_id", cid).list();

        return SpecGroupDTO.convertEntityList(specGroups);
    }
     @Autowired
     private SpecParamService specParamService;

    //TODO 根据分类id查询规格组及组内参数
    @Override
    public List<SpecGroupDTO> listSpecGroup(Long cid) {
        //根据分类ID查询规格组集合
        List<SpecGroupDTO> specGroupDTOS = listSpecGroupByCid(cid);
        //根据分类ID查询所有的规格参数
        List<SpecParamDTO> specParamDTOS = specParamService.listSpecParam(cid, null, null);
        //根据groupID对规格参数进行 TODO 分组 其中Map中 key就是groupID value 就是对应的规格参数集合
        Map<Long, List<SpecParamDTO>> specParamMap = specParamDTOS
                .stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getCategoryId));
        //TODO 遍历规格参数组集合,给每一个规格参数组对象,添加组内规格参数,然后转成DTO
       specGroupDTOS.forEach(specGroupDTO ->
               //TODO 从分组map中获取对应的规格参数
               specGroupDTO.setParams
                       (specParamMap.get(specGroupDTO.getCategoryId()))
               );
        return specGroupDTOS;
    }
    //删除规格组
    @Override
    public void deleteSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        boolean b = this.removeById(specGroup.getId());
        if(!b){
            throw new LyException(500,"删除失败");
        }
    }
}
